import Express from "express"
import { checkAuthServ, loginServ, registerServ, updatePwdServ, updateUserServ } from "../Service/userServ.js"
import { checkAuth } from "../middleware/checkAuth.js";
import { findUserDao } from "../Dao/userDao.js";
// 1，创建路由对象Express.Router
export const UserRouter = Express.Router()

UserRouter.post("/login",async(req,res)=>{
    const body = req.body;
    if(body?.code.toUpperCase() === req.session?.code.toUpperCase()){
        // 验证码ok
        // 查看数据库
        const json = await loginServ(body);
        res.json(json)
    }else{
        res.json({
            code:1,
            msg:"验证码错误"
        })
    }
})

UserRouter.post("/register",async(req,res)=>{
    const {username,nickname,code} = req.body;
    if(code?.toUpperCase() === req.session?.code?.toUpperCase()){
        await registerServ({username,nickname})
        res.json({
        code:0,
        msg:"注册成功"
    })
    }else{
        // 验证码没通过
        res.json({
        code:1,
        msg:"验证码错误"
    })
    }   
})

UserRouter.get('/whoami',checkAuth,async(req,res)=>{
    const user = await findUserDao(req.username);
    res.json({
        code:0,
        msg: 'ok',
        data: user
    })
})

// 路由层 处理请求，做出响应 ===> Serv ===> Dao
UserRouter.post('/checkpwd',checkAuth,async(req,res)=>{
    const {username,password} = req.body
    const result = await checkAuthServ(username,password)
    res.json(result)
})

UserRouter.post('/updatepwd',checkAuth,async(req,res)=>{
    const {username, password} = req.body
    await updatePwdServ(username,password)
    res.json({
        code: 0,
        msg:"修改成功"
    })
})
// 修改用户信息的请求
// query 用户ID
// body 修改的内容
UserRouter.put('/:id',checkAuth,async(req,res)=>{
    const id = req.params.id;
    const body = req.body;
    const result = await updateUserServ(id,body)
    res.json(result)
})